package com.jh.complicate.rpc.v2.client;

import com.jh.complicate.rpc.v2.api.RPCRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author Administrator
 * @projectName newforward
 * @title RPCNetTransport.java
 * @package com.jh.complicate.rpc.v1.client
 * @description RPC 传输
 * @date 2019/6/12 00:24
 */
public class RPCNetTransport {

    private String host;
    private int port;

    public RPCNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Object send(RPCRequest request) {
        Socket socket = null;
        Object result = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            // 建立连接
            socket = new Socket(host, port);

            // 写远程调度信息及参数给服务端
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(request);
            oos.flush();

            // 获取调用结果
            ois = new ObjectInputStream(socket.getInputStream());
            result = ois.readObject();
            return result;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}
